package com.atguigu.yygh.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.atguigu.yygh.user.utils.WXConstantPropertiesUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @FileName: WeixinApiController
 * @Author Steven
 * @Date: 2021/8/5
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    Logger logger=LoggerFactory.getLogger(WeixinApiController.class);
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 生成微信二维码
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getQrConnect() throws UnsupportedEncodingException {
        String redirectUri= URLEncoder.encode(WXConstantPropertiesUtils.WX_OPEN_REDIRECT_URL,"utf-8");
        HashMap<String,Object> map=new HashMap<>();
        map.put("appid",WXConstantPropertiesUtils.WX_OPEN_APP_ID);
        map.put("redirectUri",redirectUri);
        map.put("scope","snsapi_login");
        map.put("state",System.currentTimeMillis()+"");
        return Result.ok(map);
    }

    @GetMapping("callback")
    public String callback(String code,String state){
        //获取授权临时票据
        logger.info("微信授权服务器回调。。。。。。");
        logger.info("state=",state);
        logger.info("code=",code);
        if(StringUtils.isBlank(code)||StringUtils.isBlank(state)){
            logger.error("非法请求回调");
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
        StringBuffer baseAccessTokenUrl=new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                WXConstantPropertiesUtils.WX_OPEN_APP_ID,
                WXConstantPropertiesUtils.WX_OPEN_APP_SECRET,
                code);
        String result=null;
        try {
            result=HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("使用code换取的access_token结果 = " + result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if(StringUtils.isNotBlank(resultJson.getString("errcode"))){
            logger.error("获取access_token失败：" + resultJson.getString("errcode") + resultJson.getString("errmsg"));
            throw new YyghException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }
        String accessToken = resultJson.getString("access_token");
        String openId = resultJson.getString("openid");
        logger.info(accessToken);
        logger.info(openId);
        //根据access_token获取微信用户的基本信息
        //使用access_token换取受保护的资源：微信的个人信息
        //先根据openid进行数据库查询
        UserInfo userInfo = userInfoService.getByOpenId(openId);
        // 如果没有查到用户信息,那么调用微信个人信息获取的接口
        if(null==userInfo){
        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
        String userInfoUrl=String.format(baseUserInfoUrl, accessToken, openId);
        String resultUserInfo = null;
        try {
            resultUserInfo = HttpClientUtils.get(userInfoUrl);
        } catch (Exception e) {
            throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
        System.out.println("使用access_token获取用户信息的结果 = " + resultUserInfo);

        JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);
        if(resultUserInfoJson.getString("errcode") != null){
            logger.error("获取用户信息失败：" + resultUserInfoJson.getString("errcode") + resultUserInfoJson.getString("errmsg"));
            throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
        //解析用户信息
        String nickname = resultUserInfoJson.getString("nickname");
        String headimgurl = resultUserInfoJson.getString("headimgurl");


            //如果查询到个人信息，那么直接进行登录
            userInfo = new UserInfo();
            userInfo.setOpenid(openId);
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
        }
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        if(StringUtils.isEmpty(userInfo.getPhone())) {
            map.put("openid", userInfo.getOpenid());
        } else {
            map.put("openid", "");
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return "redirect:" + WXConstantPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"));
    }

}
